package com.woniu.utils;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.woniu.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
public class WebFluxUtil {
    public static Mono<Void> JWTokenFailed(ServerWebExchange exchange) {
        log.error("登录失败");
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(
                Mono.just(
                        response.bufferFactory().wrap(
                                JSONUtil.toJsonStr(
                                        ResData.failed(10000, "JWT认证失败")
                                ).getBytes(StandardCharsets.UTF_8)
                        )
                )
        );
    }

    public static UserDto getUserInfo(WebFilterExchange webFilterExchange) {
        String JWToken = webFilterExchange.getExchange().getRequest().getHeaders().get("JWToken").get(0);
        return JSONUtil.toBean(JWTUtil.parseToken(JWToken).getPayloads(), UserDto.class);
    }
}
